package com.stark.commons.spring.web.support.exception;

import java.util.Iterator;

import javax.validation.ConstraintViolationException;
import javax.validation.Path.Node;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

/**
 * {@link ConstraintViolationException} 异常处理器。
 * <p>返回 <code>400</code>状态码及错误信息。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 */
public class ConstraintViolationExceptionHandler implements ExceptionHandler {

	@Override
	public boolean instanceofException(Exception ex) {
		return ex instanceof ConstraintViolationException;
	}

	@Override
	public ResponseEntity<String> handle(Exception ex) {
		String errmsg = ((ConstraintViolationException) ex).getConstraintViolations()
				.stream()
				.map(violation -> {
					String fieldName = "";
					Iterator<Node> iter = violation.getPropertyPath().iterator();
					while (iter.hasNext()) {
						fieldName = iter.next().getName();
					}
					return fieldName + ":" + violation.getMessage();
				})
				.reduce("", (str1, str2) -> str1 + ("".equals(str1) ? "" : "\n") + str2);
		return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errmsg);
	}

}
